package com.gj.xxl.job.core.thread;

import com.gj.xxl.job.core.biz.AdminBiz;
import com.gj.xxl.job.core.biz.model.RegistryParam;
import com.gj.xxl.job.core.executor.GjJobSpringExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 执行器注册线程
 */
public class ExecutorRegistryThread {

    private static final Logger logger = LoggerFactory.getLogger(ExecutorRegistryThread.class);


    private static ExecutorRegistryThread instance = new ExecutorRegistryThread();

    public static ExecutorRegistryThread getInstance() {
        return instance;
    }

    //注册线程，不仅仅只是启动的时候注册一次，每隔 30s 都会向调度中心注册一次，实现心跳机制
    private Thread registryThread;

    private volatile boolean toStop = false;
    private int registryGapTime = 30;

    public void start(String appname, String address) {
        registryThread = new Thread(() -> {
            while (!toStop) {
                //拿到调度中心的地址，然后发送注册消息
                AdminBiz adminBiz = GjJobSpringExecutor.getAdminBizList().get(0);
                adminBiz.registry(new RegistryParam(appname, address));
                try {
                    Thread.sleep(registryGapTime * 1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        registryThread.setName("registryThread");
        registryThread.setDaemon(true);
        registryThread.start();
        logger.info(">>>>>>>>>> registryThread start");
    }

    public void toStop() {
        toStop = true;
    }

}
